package controller

import (
	"data-system/common"
	"data-system/dao"
	"data-system/excel"
	"data-system/models"
	"fmt"
	"log"

	"github.com/gin-gonic/gin"
)

func Save(c *gin.Context) {
	var data models.NodeData
	if err := c.Bind(&data); err != nil {
		log.Println(fmt.Errorf("参数解析异常,%v", err))
		c.JSON(models.FailData(err.Error()))
		return
	}
	dbData, err := dao.QueryById(data.NodeType, data.Id)
	if err != nil {
		errorMsg := fmt.Sprintf("【%v - %v】查询数据失败", data.NodeType, data.Id)
		log.Println(errorMsg)
		c.JSON(models.FailData(errorMsg))
		return
	}
	if dbData != nil {
		data.Md5 = dbData.Md5
	}
	data.Stat = common.StatUpdate
	err = dao.Save(data)
	if err != nil {
		log.Println(err.Error())
		c.JSON(models.FailData(err.Error()))
		return
	}
	//同步
	excel.DBToExcel(data.NodeType, false)
	c.JSON(models.Ok())
}

func Delete(c *gin.Context) {
	req := struct {
		NodeType string  `json:"nodeType"`
		Ids      []int64 `json:"ids"`
	}{}
	if err := c.Bind(&req); err != nil {
		log.Println(fmt.Errorf("参数解析异常,%v", err))
		c.JSON(models.FailData(err.Error()))
		return
	}
	for _, id := range req.Ids {
		err := dao.Delete(req.NodeType, id)
		if err != nil {
			log.Println(err.Error())
			c.JSON(models.FailData(err.Error()))
			return
		}
	}
	excel.DBToExcel(req.NodeType, false)
	c.JSON(models.Ok())
}
